package com.taxi.driver.module.main.duty;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.qianxx.view.loadingview.RingLoading;
import com.taxi.driver.BuildConfig;
import com.taxi.driver.R;
import com.taxi.driver.common.BaseFragment;
import com.taxi.driver.module.main.MainActivity;
import com.taxi.driver.module.main.duty.dagger.DaggerDutyComponent;
import com.taxi.driver.module.main.duty.dagger.DutyModule;
import com.taxi.driver.module.order.popup.OrderPopupActivity;
import com.taxi.driver.socket.SocketService;
import com.taxi.driver.util.Navigate;
import com.taxi.driver.util.ScreenUtil;
import com.taxi.driver.util.SpeechUtil;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 功能描述："出车/收车/继续接单/暂停接单"
 */
public class DutyFragment extends BaseFragment implements DutyContract.View {

    public static DutyFragment newInstance() {
        return new DutyFragment();
    }

    @BindView(R.id.tv_setting)
    TextView mTvSetting;
    @BindView(R.id.tv_off_duty)
    TextView mTvOffDuty;
    @BindView(R.id.tv_on_duty)
    TextView mTvOnDuty;
    @BindView(R.id.ring_loading)
    RingLoading mRingLoading;

    @Inject
    DutyPresenter mPresenter;

    // 网络是否正常
    private boolean isNetwork = true;
    private boolean isSocket = true;
    private boolean isLocation = true;
    // 是否出车
    private boolean isOnDuty;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_duty, container, false);
        ButterKnife.bind(this, mView);
        mPresenter.onCreate();
//        SpeechUtil.init(this.getActivity(), getResources().getString(R.string.xfyun_id), null);
        if (BuildConfig.FLAVOR_project.contains("Q201705XuanXuan")) {
            mTvSetting.setVisibility(View.GONE);
        }

        RxView.clicks(mTvOffDuty)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(aVoid -> mPresenter.reqOffduty());

        RxView.clicks(mTvOnDuty)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(aVoid -> mPresenter.reqOnduty());

        return mView;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        DaggerDutyComponent.builder()
                .appComponent(getAppComponent())
                .dutyModule(new DutyModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.subscribe();
//        SpeechUtil.stop(getActivity());

        if (ScreenUtil.isServiceWorked(getContext(), "com.taxi.driver.socket.SocketService")) {
            mPresenter.reqDutyStatus();
        } else {
            SocketService.startService(getActivity(), () -> mPresenter.reqDutyStatus());
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.unsubscribe();
    }

    @Override
    public void onStop() {
        super.onStop();

        if (ScreenUtil.isBackground(getActivity()) && isOnDuty) {
            SpeechUtil.speech(getActivity(), "您现在是出车中，进入后台超过5分钟可能会导致接不到单，请及时回到应用");
            Intent intent = new Intent(getActivity(), MainActivity.class);
            PendingIntent pi = PendingIntent.getActivity(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            Notification notification = new Notification.Builder(getActivity())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("您现在是出车中，进入后台超过5分钟可能会导致接不到单，请及时回到应用")
                    .setContentText("进入应用")
                    .setAutoCancel(true)
                    .setContentIntent(pi)
                    .build();
            NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(10001, notification);
        }
    }

//    @Override
//    public void onDestroy()
//    {
//        super.onDestroy();
//        SpeechUtil.stop(getActivity());
//    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.onDestory();
//        SpeechUtil.stop(getActivity());
    }

    @Override
    public void showDuty() {
        mTvOnDuty.setEnabled(false);
        mTvOnDuty.setText(R.string.duty_connecting);
        mTvOnDuty.setTextColor(Color.parseColor("#f99359"));
        mRingLoading.setRingColor(0xfff99359, 0x00f5a623);
        mRingLoading.setVisibility(View.VISIBLE);
    }

    @Override
    public void showOnDuty() {
        isOnDuty = true;
        dutyStatus();
    }

    private void dutyStatus() {
        if (isOnDuty) {
            if (isNetwork && isSocket && isLocation) {
                mTvOnDuty.setText(R.string.duty_listening);
                mTvOnDuty.setTextColor(Color.parseColor("#27b5fd"));
                mRingLoading.setRingColor(0xff27b5fd, 0x00f5a623);
                mTvOnDuty.setEnabled(false);
                mRingLoading.setVisibility(View.VISIBLE);
            } else {
                mTvOnDuty.setEnabled(false);
                mTvOnDuty.setText(R.string.duty_connecting);
                mTvOnDuty.setTextColor(Color.parseColor("#f99359"));
                mRingLoading.setRingColor(0xfff99359, 0x00f5a623);
                mRingLoading.setVisibility(View.VISIBLE);
            }
            mTvOffDuty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showOffDuty() {
        isOnDuty = false;
        mTvOnDuty.setTextColor(Color.parseColor("#27b5fd"));
        mTvOnDuty.setText(R.string.duty_on);
        mTvOnDuty.setEnabled(true);
        mRingLoading.setVisibility(View.GONE);
        mTvOffDuty.setVisibility(View.GONE);
    }

    @Override
    public void openOrderPopup(String orderUuid, boolean isAssign) {
        OrderPopupActivity.start(getContext(), orderUuid, isAssign);
    }

    @Override
    public void showNetwork(boolean network) {
        isNetwork = network;
        dutyStatus();
    }

    @Override
    public void showLocation(boolean location) {
        if (location == isLocation) {
            return;
        }
        isLocation = location;
        dutyStatus();
    }

    @Override
    public void showSocket(boolean socket) {
        if (socket == isSocket) {
            return;
        }
        isSocket = socket;
        dutyStatus();
    }

    @OnClick({R.id.tv_setting})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_setting:
                SpeechUtil.speech(getContext(), "设置模式");
                Navigate.openOrderSetting(getContext());
                break;
        }
    }
}
